//
//  MainViewController.swift
//  xlwb-swift
//
//  Created by 王世清 on 16/4/17.
//  Copyright © 2016年 wsq. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    // MARK: - composed按钮点击事件
    @objc private func didClickComposedButton() {
        print("点我了")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
        
        //打印空，说明创建控制器的时候不会添加view
//        print(tabBar.subviews)
        addComposedButton()
    }
    override func viewWillAppear(animated: Bool) {
        
        //-------会创建tabbar中的控制器view
        super.viewWillAppear(animated)
        //
        tabBar.bringSubviewToFront(composedButton)
        
//        print(tabBar.subviews)
        
    }
    // MARK: - 懒加载button
    ///便利构造函数 创建button
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")

}

// MARK: - 设置界面
extension MainViewController {
    /// 添加按钮
    private func addComposedButton() {
        
        tabBar.addSubview(composedButton)
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count) - 1
        //-------------
        composedButton.frame = CGRectInset(tabBar.bounds, w * 2, 0)
        
        //按钮注册点击事件
        composedButton.addTarget(self, action: "didClickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    
    ///添加tabBar控制器s
    private func addChildViewControllers() {
//        //渲染tabbar颜色 --- 放在全局里更好
//        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_message_center")
        //button的位置
        addChildViewController(UIViewController())
        addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileViewController(), title: "我", imageName: "tabbar_profile")
        
    }

    /// 添加控制器方法
    ///
    /// - parameter vc:        控制器
    /// - parameter title:     控制器title
    /// - parameter imageName: item图片
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        
        vc.title = title
        //=========?????????????怎么能点出 - 子控制器？
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

}
